package cn.zh.order.service.impl;

import cn.zh.order.domain.entity.Order;
import cn.zh.order.domain.entity.OrderStatus;
import cn.zh.order.domain.vo.OrderVo;
import cn.zh.order.mapper.OrderMapper;
import cn.zh.order.service.OrderServiceSeataTcc;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


/**
 * @author zh
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceSeataTccImpl implements OrderServiceSeataTcc {

    private final OrderMapper orderMapper;

    @Override
    public Integer prepareSaveOrder(OrderVo orderVo) {

        // 保存订单
        Order order = new Order();
        order.setUserId(orderVo.getUserId());
        order.setCommodityCode(orderVo.getCommodityCode());
        order.setCount(orderVo.getCount());
        order.setMoney(orderVo.getMoney());
        order.setStatus(OrderStatus.INIT.getValue());
        Integer saveOrderRecord = orderMapper.insert(order);
        log.info("保存订单{}", saveOrderRecord > 0 ? "成功" : "失败");

        BusinessActionContextUtil.addContext("orderId", order.getId());
        return saveOrderRecord;
    }

    @Override
    public void commit(BusinessActionContext actionContext) {
        // 获取订单id
        Integer orderId = Integer.parseInt(actionContext.getActionContext("orderId").toString());
        //更新订单状态为支付成功
        Integer updateOrderRecord = orderMapper.updateOrderStatus(orderId, OrderStatus.SUCCESS.getValue());
        log.info("更新订单id:{} {}", orderId, updateOrderRecord > 0 ? "成功" : "失败");
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        //获取订单id
        Integer orderId = Integer.parseInt(actionContext.getActionContext("orderId").toString());

        //更新订单状态为支付失败
        Integer updateOrderRecord = orderMapper.updateOrderStatus(orderId, OrderStatus.FAIL.getValue());
        log.info("更新订单id:{} {}", orderId, updateOrderRecord > 0 ? "成功" : "失败");

        return true;
    }
}
